<script setup>
import {ref, reactive} from 'vue'
import {useUserStore} from '@/stores/userStore.js'

const userStore = useUserStore()
const dialogVisible = ref(false)

// 用户详情数据结构（与API返回格式匹配）
const userDetail = reactive({
  userId: null,
  username: '',
  realName: '',
  email: '',
  mobile: '',
  deptId: null,
  deptName: '',
  status: '',
  roleIds: [],
  roleNames: [],
  createdTime: null
})


const show = async (userInfo) => {
  try {
    // 调用获取用户详情接口
    const res = await userStore.getUserDetail(userInfo.id);
    if (res) {
      Object.assign(userDetail, res);
    }
  } catch (error) {
    console.error('获取用户详情失败:', error);
  }
  dialogVisible.value = true
}

// 自定义时间格式化函数
const formatCreatedTime = (dateValue) => {
  if (!dateValue) return '无';

  try {
    // 尝试创建日期对象
    const date = new Date(dateValue);

    // 检查是否为有效日期
    if (isNaN(date.getTime())) {
      return dateValue; // 如果无效，直接返回原始值
    }

    // 格式化为 YYYY-MM-DD HH:mm:ss
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateValue || '无';
  }
}

// 手机号模糊显示函数
const formatMobile = (mobile) => {
  if (!mobile) return '无';

  const mobileStr = String(mobile);

  // 检查是否为有效的手机号格式（11位数字）
  if (mobileStr.length === 11 && /^\d+$/.test(mobileStr)) {
    return mobileStr.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }

  return mobileStr;
}

const close = () => {
  dialogVisible.value = false
}

// 对外暴露show方法
defineExpose({show})
</script>

<template>
  <el-dialog
      v-model="dialogVisible"
      title="用户详情"
      width="50%"
      :before-close="close"
  >
    <el-descriptions :column="1" border>
      <!-- 确保所有字段与API数据结构匹配 -->
      <el-descriptions-item label="用户ID">{{ userDetail.userId || '无' }}</el-descriptions-item>
      <el-descriptions-item label="账号">{{ userDetail.username || '无' }}</el-descriptions-item>
      <el-descriptions-item label="姓名">{{ userDetail.realName || '无' }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ formatMobile(userDetail.mobile) }}</el-descriptions-item>
      <el-descriptions-item label="邮箱">{{ userDetail.email || '无' }}</el-descriptions-item>
      <el-descriptions-item label="所属部门">
        {{ userDetail.deptName || '无' }} <span v-if="userDetail.deptId">(ID: {{ userDetail.deptId }})</span>
      </el-descriptions-item>
      <el-descriptions-item label="角色">
        <template v-if="userDetail.roleNames && userDetail.roleNames.length">
          <el-tag v-for="(role,index) in userDetail.roleNames" :key="index" type="info" class="mr-2">
            {{ role }}
          </el-tag>
        </template>
        <span v-else>无</span>
      </el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="userDetail.status === 1 ? 'success' : 'danger'">
          {{ userDetail.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ formatCreatedTime(userDetail.createdTime) }}
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 调整描述列表样式 */
.el-descriptions {
  margin: -10px 0;
}

/* 标签间距 */
.mr-2 {
  margin-right: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
  }
}
</style>
